package com.example.administrator.newsreading;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.administrator.newsreading.Bean.news;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;


/**
 * Created by Administrator on 2016/4/24.
 */
public class detail extends Activity{
    private TextView textView;

    private String ID = null;
    private String title = null;
    private String source = null;
    private String time = null;
    private String image_url = null;
    private String passage = null;

    private ImageView imageView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //设置当前Activity的界面布局
        setContentView(R.layout.detail);
        //获得Intent
        Intent intent = this.getIntent();

        //从上一个界面传过来的新闻ID值
        ID = intent.getStringExtra("ID");

        //通过ID查询各字段的值，并把值添加到界面上
        query_news_detail(ID);

    }

    //通过ID查询各字段的值，并把值添加到界面上
    public void query_news_detail(String ID){
        BmobQuery<news> query = new BmobQuery<news>();

        query.addWhereEqualTo("ID", ID);
        query.findObjects(this, new FindListener<news>() {
            @Override
            public void onSuccess(List<news> list) {
                title = list.get(0).getTitle();
                source = list.get(0).getSource();
                time = list.get(0).getTime();
                image_url = list.get(0).getImage_url();
                passage = list.get(0).getPassage();

                //设置标题
                textView = (TextView) findViewById(R.id.detail_title);
                textView.setText(title);

                //设置来源
                textView = (TextView) findViewById(R.id.detail_source);
                textView.setText(convert_source(source));

                //设置时间
                textView = (TextView) findViewById(R.id.detail_time);
                textView.setText(convert_time(time));

                //设置图片，必须用多线程的方法
                Thread thread = new Thread(runnable);
                thread.start();


                //设置正文
                textView = (TextView) findViewById(R.id.detail_passage);
                textView.setText(passage.replace("|||", "\n\n\n"));//将原来的换行标志（空格或者|||）替换成\n
            }

            @Override
            public void onError(int i, String s) {
                /*Toast.makeText(detail.this, "Error", Toast.LENGTH_SHORT).show();*/
            }
        });
    }

    //转换来源信息
    private String convert_source(String source){
        String result = null;
        if(source.equals("sina")){
            result = "新浪";
        }
        else if (source.equals("tencent")){
            result = "腾讯";
        }
        else if (source.equals("netease")){
            result = "网易";
        }
        return result;
    }

    //转换时间信息，将12位的时间转化为mm-dd hh:mm
    private String convert_time(String time){
        String result;
        String month, day, hour, minute;
        month = time.substring(4,6);
        day = time.substring(6,8);
        hour = time.substring(8,10);
        minute = time.substring(10,12);

        result = month + "-" + day + " " + hour + ":" + minute;

        return result;
    }

    //线程里获取网络图片
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            URL myFileUrl = null;
            InputStream inputStream = null;
            Bitmap bitmap = null;

            if((image_url+"a").length() > 10) {
                try {
                    myFileUrl = new URL(image_url);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }

                try {
                    HttpURLConnection connection = (HttpURLConnection) myFileUrl.openConnection();
                    connection.setConnectTimeout(3000);//超时时间为3秒
                    connection.setRequestMethod("GET");//请求方法设为GET
                    connection.setDoInput(true);//打开输入流

                    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { //正常连接
                        inputStream = connection.getInputStream();//获取输入流
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                bitmap = BitmapFactory.decodeStream(inputStream);//转换InputStream为Bitmap
                handler.obtainMessage(1, bitmap).sendToTarget();
            }
            else
                handler.sendEmptyMessage(0);
        }
    };

    //更改UI信息，将获取到的网络图片放到ImageView
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    break;
                case 1:
                    imageView = (ImageView)findViewById(R.id.detail_image);
                    imageView.setImageBitmap((Bitmap) msg.obj);
                    break;
            }
        }
    };

}
